package com.easemob.cloud;

import android.content.Context;
import android.text.TextUtils;
import com.easemob.analytics.EMPerformanceCollector;
import com.easemob.analytics.EMTimeTag;
import com.easemob.chat.core.f;
import com.easemob.chat.core.f.c;
import com.easemob.chat.core.k;
import com.easemob.util.EMLog;
import com.easemob.util.NetUtils;
import internal.org.apache.http.entity.mime.content.FileBody;
import internal.org.apache.http.entity.mime.content.StringBody;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpFileManager extends CloudFileManager
{
  private static final long MAX_ALLOWED_FILE_SIZE = 10485760L;
  private long totalSize;
  private Context appContext;
  boolean tokenRetrieved = false;
  private static final int max_retry_times_on_connection_refused = 20;

  public HttpFileManager(Context paramContext, String paramString)
  {
    this.appContext = paramContext.getApplicationContext();
  }

  public HttpFileManager(Context paramContext)
  {
    this.appContext = paramContext.getApplicationContext();
  }

  public boolean authorization()
  {
    return true;
  }

  private void sendFiletoServerHttp(String paramString1, String paramString2, String paramString3, String paramString4, Map<String, String> paramMap, CloudOperationCallback paramCloudOperationCallback)
  {
    sendFiletoServerHttpWithCountDown(paramString1, paramString2, paramString3, paramString4, paramMap, paramCloudOperationCallback, -1, false);
  }

  private void sendFiletoServerHttpWithCountDown(final String paramString1, final String paramString2, final String paramString3, final String paramString4, Map<String, String> paramMap, final CloudOperationCallback paramCloudOperationCallback, int paramInt, boolean paramBoolean)
  {
    File localFile = new File(paramString1);
    if (!localFile.isFile())
    {
      EMLog.e("CloudFileManager", "Source file doesn't exist");
      paramCloudOperationCallback.onError("Source file doesn't exist");
      return;
    }
    if (localFile.length() > 10485760L)
    {
      paramCloudOperationCallback.onError("file doesn't bigger than 10 M");
      return;
    }
    final Map localMap = HttpClientManager.addDomainToHeaders(paramMap);
    HttpResponse localHttpResponse = null;
    String str1 = HttpClientConfig.getFileRemoteUrl(paramString2);
    EMLog.d("CloudFileManager", " remote path url : " + str1 + " --countDown: " + paramInt);
    DefaultHttpClient localDefaultHttpClient = HttpClientConfig.getDefaultHttpClient();
    try
    {
      HttpPost localHttpPost = new HttpPost(str1);
      localObject1 = new CustomMultiPartEntity(new CustomMultiPartEntity.ProgressListener()
      {
        public void transferred(long paramAnonymousLong)
        {
          int i = (int)((float)paramAnonymousLong / (float)HttpFileManager.this.totalSize * 100.0F);
          if ((i != 100) && (paramCloudOperationCallback != null))
            paramCloudOperationCallback.onProgress(i);
        }
      });
      if (paramString3 != null)
        ((CustomMultiPartEntity)localObject1).addPart("app", new StringBody(paramString3));
      if (paramString4 != null)
        ((CustomMultiPartEntity)localObject1).addPart("id", new StringBody(paramString4));
      if (localMap != null)
      {
        localObject3 = localMap.entrySet().iterator();
        while (((Iterator)localObject3).hasNext())
        {
          localObject2 = (Map.Entry)((Iterator)localObject3).next();
          localHttpPost.addHeader((String)((Map.Entry)localObject2).getKey(), (String)((Map.Entry)localObject2).getValue());
        }
      }
      localObject2 = paramString2;
      if (((String)localObject2).indexOf("/") > 0)
      {
        localObject3 = ((String)localObject2).substring(0, ((String)localObject2).lastIndexOf("/"));
        localObject2 = ((String)localObject2).substring(((String)localObject2).lastIndexOf("/"));
        ((CustomMultiPartEntity)localObject1).addPart("path", new StringBody((String)localObject3));
      }
      localObject3 = getMimeType(localFile);
      EMLog.d("CloudFileManager", " remote file name : " + (String)localObject2);
      ((CustomMultiPartEntity)localObject1).addPart("file", new FileBody(localFile, (String)localObject2, (String)localObject3, "UTF-8"));
      this.totalSize = ((CustomMultiPartEntity)localObject1).getContentLength();
      localHttpPost.setEntity((HttpEntity)localObject1);
      if (k.a().B())
        HttpClientManager.checkAndProcessSSL(str1, localDefaultHttpClient);
      EMTimeTag localEMTimeTag = new EMTimeTag();
      localEMTimeTag.start();
      localHttpResponse = localDefaultHttpClient.execute(localHttpPost);
      localEMTimeTag.stop();
      if (localEMTimeTag.timeSpent() > 0L)
        EMPerformanceCollector.collectUploadFileTime(localEMTimeTag, this.totalSize, str1);
      int j = localHttpResponse.getStatusLine().getStatusCode();
      EMLog.d("CloudFileManager", "server responseCode:" + j + " localFilePath : " + paramString1);
      switch (j)
      {
      case 200:
        paramCloudOperationCallback.onProgress(100);
        HttpEntity localHttpEntity1 = localHttpResponse.getEntity();
        str2 = EntityUtils.toString(localHttpEntity1);
        paramCloudOperationCallback.onSuccess(str2);
        return;
      case 401:
        long l = k.a().r();
        if (System.currentTimeMillis() - l <= 600000L)
        {
          if (paramCloudOperationCallback != null)
            paramCloudOperationCallback.onError("unauthorized file");
          return;
        }
        if (this.tokenRetrieved)
        {
          paramCloudOperationCallback.onError("unauthorized file");
          return;
        }
        String str3 = retryToGetToken();
        this.tokenRetrieved = true;
        if (str3 == null)
        {
          paramCloudOperationCallback.onError("unauthorized token is null");
          return;
        }
        localMap.put("Authorization", "Bearer " + str3);
        if (!paramBoolean)
        {
          new Thread()
          {
            public void a()
            {
              HttpFileManager.this.sendFiletoServerHttpWithCountDown(paramString1, paramString2, paramString3, paramString4, localMap, paramCloudOperationCallback, 3, true);
            }
          }
          .start();
        }
        else if (paramInt > 0)
        {
          paramInt--;
          final int k = paramInt;
          new Thread()
          {
            public void a()
            {
              HttpFileManager.this.sendFiletoServerHttpWithCountDown(paramString1, paramString2, paramString3, paramString4, localMap, paramCloudOperationCallback, k, true);
            }
          }
          .start();
        }
        return;
      }
      HttpEntity localHttpEntity2 = localHttpResponse.getEntity();
      String str2 = EntityUtils.toString(localHttpEntity2);
      str2 = "Http response error : " + j + " error msg : " + str2;
      EMLog.e("CloudFileManager", str2);
      if (paramCloudOperationCallback != null)
        paramCloudOperationCallback.onError(str2);
      return;
    }
    catch (Exception localException)
    {
      Object localObject3;
      Object localObject2;
      Object localObject1 = (localException != null) && (localException.getMessage() != null) ? localException.getMessage() : "failed to upload the files";
      EMLog.e("CloudFileManager", "sendFiletoServerHttp:" + (String)localObject1);
      if ((k.a().d()) && (((String)localObject1).toLowerCase().contains("refused")) && (NetUtils.hasNetwork(this.appContext)))
      {
        if (!paramBoolean)
        {
          localObject2 = f.a().g();
          localObject3 = HttpClientManager.getNewHost(paramString2, (f.c)localObject2);
          new Thread()
          {
            public void a()
            {
              HttpFileManager.this.sendFiletoServerHttpWithCountDown(paramString1, this.c, paramString3, paramString4, localMap, paramCloudOperationCallback, 20, true);
            }
          }
          .start();
          return;
        }
        if (paramInt > 0)
        {
          localObject2 = f.a().g();
          localObject3 = HttpClientManager.getNewHost(str1, (f.c)localObject2);
          paramInt--;
          final int i = paramInt;
          new Thread()
          {
            public void a()
            {
              HttpFileManager.this.sendFiletoServerHttpWithCountDown(paramString1, this.c, paramString3, paramString4, localMap, paramCloudOperationCallback, i, true);
            }
          }
          .start();
          return;
        }
      }
      if (paramCloudOperationCallback != null)
        paramCloudOperationCallback.onError((String)localObject1);
    }
  }

  public static String getMimeType(File paramFile)
  {
    String str = paramFile.getName();
    if ((str.endsWith(".3gp")) || (str.endsWith(".amr")))
      return "audio/3gp";
    if ((str.endsWith(".jpe")) || (str.endsWith(".jpeg")) || (str.endsWith(".jpg")))
      return "image/jpeg";
    if (str.endsWith(".amr"))
      return "audio/amr";
    if (str.endsWith(".mp4"))
      return "video/mp4";
    return "image/png";
  }

  public void uploadFileInBackground(final String paramString1, final String paramString2, final String paramString3, final String paramString4, final Map<String, String> paramMap, final CloudOperationCallback paramCloudOperationCallback)
  {
    new Thread()
    {
      public void a()
      {
        try
        {
          HttpFileManager.this.sendFiletoServerHttp(paramString1, paramString2, paramString3, paramString4, paramMap, paramCloudOperationCallback);
        }
        catch (Exception localException)
        {
          if ((localException != null) && (localException.getMessage() != null))
          {
            EMLog.e("CloudFileManager", localException.getMessage());
            paramCloudOperationCallback.onError(localException.toString());
          }
          else
          {
            paramCloudOperationCallback.onError("failed to upload the file : " + paramString1 + " remote path : " + paramString2);
          }
        }
      }
    }
    .start();
  }

  public void uploadFile(String paramString1, String paramString2, String paramString3, String paramString4, Map<String, String> paramMap, CloudOperationCallback paramCloudOperationCallback)
  {
    try
    {
      sendFiletoServerHttp(paramString1, paramString2, paramString3, paramString4, paramMap, paramCloudOperationCallback);
    }
    catch (Exception localException)
    {
      EMLog.e("CloudFileManager", "uploadFile error:" + localException.getMessage());
      paramCloudOperationCallback.onError(localException.toString());
    }
  }

  public void downloadFile(String paramString1, String paramString2, String paramString3, Map<String, String> paramMap, CloudOperationCallback paramCloudOperationCallback)
  {
    if (TextUtils.isEmpty(paramString1))
    {
      if (paramCloudOperationCallback != null)
        paramCloudOperationCallback.onError("remotefilepath is null or empty");
      EMLog.e("CloudFileManager", "remotefilepath is null or empty");
    }
    else
    {
      String str = HttpClientConfig.getFileRemoteUrl(paramString1);
      downloadFile(str, paramString2, paramMap, paramCloudOperationCallback);
    }
  }

  public void downloadFile(String paramString1, String paramString2, Map<String, String> paramMap, CloudOperationCallback paramCloudOperationCallback)
  {
    try
    {
      downloadFileWithCountDown(paramString1, paramString2, paramMap, paramCloudOperationCallback, 20);
    }
    catch (Exception localException)
    {
      String str = "failed to download file : " + paramString1;
      if ((localException != null) && (localException.getMessage() != null))
        str = localException.getMessage();
      if (paramCloudOperationCallback != null)
        paramCloudOperationCallback.onError(str);
    }
  }

  private void downloadFileWithCountDown(String paramString1, final String paramString2, Map<String, String> paramMap, final CloudOperationCallback paramCloudOperationCallback, int paramInt)
  {
    if ((paramString1 == null) || (paramString1.length() <= 0))
    {
      paramCloudOperationCallback.onError("invalid remoteUrl");
      return;
    }
    final Map localMap = HttpClientManager.addDomainToHeaders(paramMap);
    paramString1 = HttpClientConfig.getFileRemoteUrl(paramString1);
    EMLog.d("CloudFileManager", "remoteUrl:" + paramString1 + " localFilePath:" + paramString2);
    paramString1 = processUrl(paramString1);
    EMLog.d("CloudFileManager", "download file: remote url : " + paramString1 + " , local file : " + paramString2);
    File localFile = new File(paramString2);
    EMLog.d("CloudFileManager", "local exists:" + localFile.exists());
    if (!localFile.getParentFile().exists())
      localFile.mkdirs();
    EMTimeTag localEMTimeTag = new EMTimeTag();
    localEMTimeTag.start();
    DefaultHttpClient localDefaultHttpClient = HttpClientConfig.getDefaultHttpClient();
    try
    {
      HttpGet localHttpGet = new HttpGet(paramString1);
      processHeaders(localHttpGet, localMap);
      HttpClientManager.checkAndProcessSSL(paramString1, localDefaultHttpClient);
      localObject = localDefaultHttpClient.execute(localHttpGet);
      int i = ((HttpResponse)localObject).getStatusLine().getStatusCode();
      long l;
      switch (i)
      {
      case 200:
        l = onDownloadCompleted((HttpResponse)localObject, paramCloudOperationCallback, paramString2);
        if (l <= 0L)
        {
          if (paramCloudOperationCallback != null)
            paramCloudOperationCallback.onError("downloaded content size is zero!");
          return;
        }
        localEMTimeTag.stop();
        if (localEMTimeTag.timeSpent() > 0L)
          EMPerformanceCollector.collectDownloadFileTime(localEMTimeTag, l, paramString1);
        if (paramCloudOperationCallback != null)
          paramCloudOperationCallback.onSuccess("download successfully");
        break;
      case 401:
        l = k.a().r();
        if (System.currentTimeMillis() - l <= 600000L)
        {
          if (paramCloudOperationCallback != null)
            paramCloudOperationCallback.onError("unauthorized file");
          return;
        }
        if (this.tokenRetrieved)
        {
          if (paramCloudOperationCallback != null)
            paramCloudOperationCallback.onError("unauthorized file");
          return;
        }
        final String str2 = paramString1;
        new Thread()
        {
          public void a()
          {
            String str = HttpFileManager.this.retryToGetToken();
            if (str == null)
            {
              paramCloudOperationCallback.onError("unauthorized token is null");
              return;
            }
            HttpFileManager.this.tokenRetrieved = true;
            if (localMap != null)
            {
              localMap.put("Authorization", "Bearer " + str);
              HttpFileManager.this.downloadFile(str2, paramString2, localMap, paramCloudOperationCallback);
            }
            else if (paramCloudOperationCallback != null)
            {
              paramCloudOperationCallback.onError("unauthorized token is null");
            }
          }
        }
        .start();
        break;
      default:
        EMLog.e("CloudFileManager", "error response code is :" + i);
        if (paramCloudOperationCallback != null)
          paramCloudOperationCallback.onError(String.valueOf(i));
        break;
      }
    }
    catch (Exception localException)
    {
      Object localObject = localException.getMessage();
      if (localObject == null)
        localObject = "failed to download file";
      if ((k.a().d()) && (((String)localObject).toLowerCase().contains("refused")) && (NetUtils.hasNetwork(this.appContext)) && (paramInt > 0))
      {
        f.c localc = f.a().g();
        final String str1 = HttpClientManager.getNewHost(paramString1, localc);
        paramInt--;
        final int j = paramInt;
        new Thread()
        {
          public void a()
          {
            try
            {
              HttpFileManager.this.downloadFileWithCountDown(str1, paramString2, localMap, paramCloudOperationCallback, j);
            }
            catch (Exception localException)
            {
              if ((localException != null) && (localException.getMessage() != null))
                paramCloudOperationCallback.onError(localException.getMessage());
              else
                paramCloudOperationCallback.onError("failed to download the file : " + str1);
            }
          }
        }
        .start();
        return;
      }
      EMLog.e("CloudFileManager", (String)localObject);
      if (paramCloudOperationCallback != null)
        paramCloudOperationCallback.onError((String)localObject);
    }
  }

  private String processUrl(String paramString)
  {
    if (paramString.contains("+"))
      paramString = paramString.replaceAll("+", "%2B");
    if (paramString.contains("#"))
      paramString = paramString.replaceAll("#", "%23");
    return paramString;
  }

  private void processHeaders(HttpGet paramHttpGet, Map<String, String> paramMap)
  {
    paramHttpGet.addHeader("Authorization", "Bearer " + k.a().q());
    paramHttpGet.addHeader("Accept", "application/octet-stream");
    if (paramMap != null)
    {
      Iterator localIterator = paramMap.entrySet().iterator();
      while (localIterator.hasNext())
      {
        Map.Entry localEntry = (Map.Entry)localIterator.next();
        if ((!((String)localEntry.getKey()).equals("Authorization")) && (!((String)localEntry.getKey()).equals("Accept")))
          paramHttpGet.addHeader((String)localEntry.getKey(), (String)localEntry.getValue());
      }
    }
  }

  private long onDownloadCompleted(HttpResponse paramHttpResponse, CloudOperationCallback paramCloudOperationCallback, String paramString)
    throws IOException, IllegalStateException
  {
    HttpEntity localHttpEntity = paramHttpResponse.getEntity();
    if (localHttpEntity == null)
      return 0L;
    InputStream localInputStream = null;
    FileOutputStream localFileOutputStream = null;
    int i = 0;
    int j = 0;
    long l1 = localHttpEntity.getContentLength();
    try
    {
      localInputStream = localHttpEntity.getContent();
    }
    catch (IllegalStateException localIllegalStateException)
    {
      localIllegalStateException.printStackTrace();
      throw localIllegalStateException;
    }
    catch (IOException localIOException1)
    {
      localIOException1.printStackTrace();
      throw localIOException1;
    }
    File localFile = new File(paramString);
    try
    {
      localFileOutputStream = new FileOutputStream(localFile);
    }
    catch (FileNotFoundException localFileNotFoundException)
    {
      localFileNotFoundException.printStackTrace();
      localInputStream.close();
      throw localFileNotFoundException;
    }
    int k = NetUtils.getDownloadBufSize(this.appContext);
    byte[] arrayOfByte = new byte[k];
    long l2 = 0L;
    try
    {
      while ((i = localInputStream.read(arrayOfByte)) != -1)
      {
        l2 += i;
        int m = (int)(l2 * 100L / l1);
        EMLog.d("HttpFileManager", m);
        if ((m == 100) || (m > j + 5))
        {
          j = m;
          if (paramCloudOperationCallback != null)
            paramCloudOperationCallback.onProgress(j);
        }
        localFileOutputStream.write(arrayOfByte, 0, i);
      }
      long l3 = localFile.length();
      return l3;
    }
    catch (IOException localIOException2)
    {
      localIOException2.printStackTrace();
      throw localIOException2;
    }
    finally
    {
      localFileOutputStream.close();
      localInputStream.close();
    }
  }

  private String retryToGetToken()
  {
    k.a().s();
    String str = null;
    int i = 3;
    while (i > 0)
    {
      str = k.a().q();
      if (str != null)
        break;
      try
      {
        Thread.sleep(2000L);
        i--;
      }
      catch (InterruptedException localInterruptedException)
      {
        localInterruptedException.printStackTrace();
      }
    }
    return str;
  }

  public void deleteFileInBackground(final String paramString1, final String paramString2, String paramString3, final CloudOperationCallback paramCloudOperationCallback)
  {
    Thread local9 = new Thread()
    {
      public void a()
      {
        HttpURLConnection localHttpURLConnection = null;
        DataOutputStream localDataOutputStream = null;
        String str1 = "\r\n";
        String str2 = "--";
        String str3 = "*****";
        String str4 = "";
        str4 = HttpClientConfig.getFileRemoteUrl(paramString1);
        try
        {
          URL localURL = new URL(str4);
          localHttpURLConnection = (HttpURLConnection)localURL.openConnection();
          localHttpURLConnection.setDoInput(true);
          localHttpURLConnection.setDoOutput(true);
          localHttpURLConnection.setUseCaches(false);
          localHttpURLConnection.setRequestMethod("POST");
          localHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
          localHttpURLConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
          localHttpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + str3);
          localHttpURLConnection.setRequestProperty("file", paramString1);
          localDataOutputStream = new DataOutputStream(localHttpURLConnection.getOutputStream());
          localDataOutputStream.writeBytes(str2 + str3 + str1);
          if (paramString2 != null)
          {
            localDataOutputStream.writeBytes("Content-Disposition: form-data; name=\"app\"" + str1 + str1);
            localDataOutputStream.writeBytes(paramString2 + str1);
            localDataOutputStream.writeBytes(str2 + str3 + str1);
          }
          localDataOutputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + paramString1 + "\"" + str1);
          localDataOutputStream.writeBytes(str1);
          BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localHttpURLConnection.getInputStream()));
          String str5;
          while ((str5 = localBufferedReader.readLine()) != null)
            EMLog.d("CloudFileManager", "RESULT Message: " + str5);
          localBufferedReader.close();
          localDataOutputStream.close();
          localHttpURLConnection.disconnect();
          if (paramCloudOperationCallback != null)
            paramCloudOperationCallback.onSuccess(null);
        }
        catch (Exception localException)
        {
          localException.printStackTrace();
          if (paramCloudOperationCallback != null)
            paramCloudOperationCallback.onError(localException.toString());
        }
      }
    };
    local9.start();
  }
}

/* Location:           D:\hygieia\userclient\common\libs\easemobchat_2.1.8.jar
 * Qualified Name:     com.easemob.cloud.HttpFileManager
 * JD-Core Version:    0.6.1
 */